package com.multicampus.simplewiki.control.openapi;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.multicampus.simplewiki.ctrl.DocumentManager;
import com.multicampus.simplewiki.model.TrackBack;

public class TrackBackController extends SimpleFormController {
	private DocumentManager documentManager;
	private final String successXml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" 
			+ "<response>" + "<error>0</error>"
			+ "<message>Your TrackBack has been registered.</message>" + "</response>";

	public void setDocumentManager(DocumentManager documentManager) {
		this.documentManager = documentManager;
	}

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		try{
			String requestUri = request.getRequestURI();
			String documetId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
	
			TrackBack trackBack = new TrackBack();
			trackBack.setTitle(request.getParameter("title"));
			trackBack.setBlogname(request.getParameter("blog_name"));
			trackBack.setUrl(request.getParameter("url"));
			trackBack.setExcerpt(request.getParameter("excerpt"));
	
			TrackBack returnValue = documentManager.addTrackBack(Integer.parseInt(documetId), trackBack);
			
			if(returnValue == null)
				throw new Exception("Wrong document id");
	
			response.setContentType("text/xml");
			response.getOutputStream().write(successXml.getBytes());
			response.flushBuffer();
			return null;
		}catch(Exception e){
			String errorXml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" 
				+ "<response>" + "<error>0</error>"
				+ "<message>Your TrackBack has error. Error message is [" + e.getMessage() + "]</message>" + "</response>";
			
			response.setContentType("text/xml");
			response.getOutputStream().write(errorXml.getBytes());
			response.flushBuffer();
			return null;
		}
	}
}
